package com.zyx.springmvc.scope.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/14 14:17
 */
@Controller
public class ScopeController {

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testServletAPI")
    public String testServletApi(HttpServletRequest request) {
        request.setAttribute("testRequestScope", "hello, ServletAPI");
        return "scope";
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        /*
            ModelAndView有Model和View的功能
                Model主要用于向请求域共享数据
                View主要用于设置视图，实现页面跳转
         */
        ModelAndView mav = new ModelAndView();
        // 向请求域共享数据
        mav.addObject("testRequestScope", "hello, ModelAndView");
        // 设置视图名称, 实现页面跳转
        mav.setViewName("scope");
        return mav;
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testModel")
    public String testModel(Model model) {
        model.addAttribute("testRequestScope", "hello, Model");
        return "scope";
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap) {
        modelMap.addAttribute("testRequestScope", "hello, ModelMap");
        return "scope";
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testSessionScope")
    public String testSessionScope(HttpSession session) {
        session.setAttribute("testSessionScope", "hello, SessionScope");
        return "scope";
    }

    @SuppressWarnings("SpringMVCViewInspection")
    @RequestMapping("/testApplicationScope")
    public String testApplicationScope(HttpSession session) {
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello, ApplicationScope");
        return "scope";
    }

}
